<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import dayjs from 'dayjs';
import runData from '@/components/ECharts/runData/index.vue';
import deviceRecording from '@/components/deviceRecording/index.vue';
import videoComManagement from '@/components/videoComManagement/index.vue';
import { defaultImage } from '@/utils/defaultImage';
import empty from '@/assets/icons/svg/empty-box.svg';
import { configKey, getPointInfo } from '@/api/earlyWarning';

interface Props {
  data: any;
  title?: string;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  close: [];
}>();

const Someday = ref<string>('');
const currentPointInfo = ref<any>(null);
const deviceRecordingRef = ref();

// 在 onMounted 中进行异步数据加载
onMounted(async () => {
  try {
    const { data } = await configKey('n_day_run');
    Someday.value = data;
    console.log(props.data);

    // 从 props.data 中获取 id 和 type
    if (props.data?.id && props.data?.type) {
      const result = await getPointInfo({ type: props.data.type, id: props.data.id });
      currentPointInfo.value = result.data;
    } else {
      // 如果没有提供足够的数据，使用 props.data 作为默认数据
      currentPointInfo.value = {
        info: props.data || {},
        data: props.data || {}
      };
    }
  } catch (error) {
    console.error('加载监测数据失败:', error);
    // 设置默认数据结构
    currentPointInfo.value = {
      info: props.data || {},
      data: props.data || {}
    };
  }
});
const timePeriod = computed(() => {
  const current = dayjs().format('YYYY-MM-DD');
  const nDay = dayjs()
    .subtract(Number(Someday.value) - 1, 'day')
    .format('YYYY-MM-DD');
  return `${nDay}至${current}`;
});
const ReportHandle = () => {
  if (deviceRecordingRef.value && typeof deviceRecordingRef.value.open === 'function') {
    deviceRecordingRef.value.open();
  } else {
    console.warn('deviceRecording组件未准备好或缺少open方法');
  }
};
// 判断是否显示echarts
const isShowECharts = computed(() => {
  return currentPointInfo.value?.data?.data && currentPointInfo.value?.data?.seriesList;
});
//格式化经纬度
const formattedNumber = computed(() => {
  if (!currentPointInfo.value?.info?.latitude || !currentPointInfo.value?.info?.longitude) {
    return '未知位置';
  }
  const lat = currentPointInfo.value.info.latitude;
  const lng = currentPointInfo.value.info.longitude;
  return `${lng},${lat}`;
});
// 处理设备状态
const sensorStatus = computed(() => {
  if (!currentPointInfo.value?.info?.sensorStatus) {
    return '#ff0000';
  }
  return currentPointInfo.value.info.sensorStatus === '在线' ? '#43ff8b' : '#ff0000';
});
//处理category字符串按照空格分割成数组 然后在渲染在模板上
const category = computed(() => {
  if (!currentPointInfo.value?.info?.category) {
    return [];
  }
  return currentPointInfo.value.info.category.split(' ');
});
//判断是否显示视频监控
const isShowVideo = computed(() => {
  if (!currentPointInfo.value?.info?.equipmentClassify) {
    return false;
  }
  return (
    currentPointInfo.value.info.equipmentClassify == '2' ||
    currentPointInfo.value.info.equipmentClassify == '3' ||
    currentPointInfo.value.info.equipmentClassify == '25'
  );
});
//切换按钮状态
const ToggleButtonName = ref('视频监控');
//点击视频监控 运行数据切换
const handleChange = () => {
  if (ToggleButtonName.value === '视频监控') {
    ToggleButtonName.value = '运行数据';
  } else {
    ToggleButtonName.value = '视频监控';
  }
};
//给特定的设备添加默认图片
const getDefaultImage = (type: string | number) => {
  return defaultImage[type] ? defaultImage[type] : false;
};
</script>

<template>
  <div class="monitor-data-popup">
    <div class="popup-header">
      <h3 class="popup-title">{{ currentPointInfo?.info?.instPos || title || '监测数据' }}</h3>
      <button class="close-btn" @click="$emit('close')">
        <svg width="16" height="16" viewBox="0 0 16 16">
          <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
        </svg>
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="!currentPointInfo" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载监测数据...</p>
    </div>

    <!-- 数据内容 -->
    <div v-else class="card-box">
      <el-row>
        <el-tag style="margin-left: 4px" size="small" v-for="item in category" :key="item" effect="dark">
          {{ item }}
        </el-tag>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="16">
          <el-descriptions :column="2" class="largeScreen-descriptions">
            <el-descriptions-item label="设备状态">
              <span :style="{ 'color': sensorStatus }">
                {{ currentPointInfo?.info?.sensorStatus || '未知' }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="设备编号">{{ currentPointInfo?.info?.code || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="应用场景">{{ currentPointInfo?.info?.monitorScenceName || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="安装位置">{{ currentPointInfo?.info?.instPos || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="经纬度">{{ formattedNumber }}</el-descriptions-item>
            <el-descriptions-item label="采集频次">{{ currentPointInfo?.info?.frequency || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="所属企业" v-if="currentPointInfo?.info?.equipmentClassify == '9'">
              {{ currentPointInfo?.info?.comName || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="窨井类型" v-if="currentPointInfo?.info?.wallType"
              >{{ currentPointInfo.info.wallType }}
            </el-descriptions-item>
            <el-descriptions-item label="详细位置" v-if="currentPointInfo?.info?.equipmentClassify == '18'"
              >{{ currentPointInfo?.info?.detailPos || '未知' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="8">
          <el-carousel height="150px" indicator-position="outside" v-if="currentPointInfo?.info?.imgUrls">
            <el-carousel-item v-for="item in currentPointInfo.info.imgUrls" :key="item">
              <el-image preview-teleported :src="item" :preview-src-list="currentPointInfo.info.imgUrls" :initial-index="0" fit="cover" />
            </el-carousel-item>
          </el-carousel>
          <el-carousel height="150px" indicator-position="outside" v-else-if="getDefaultImage(currentPointInfo?.info?.equipmentClassify)">
            <el-carousel-item>
              <el-image
                :src="getDefaultImage(currentPointInfo?.info?.equipmentClassify)"
                :preview-src-list="[getDefaultImage(currentPointInfo?.info?.equipmentClassify)]"
                :initial-index="0"
                preview-teleported
                fit="cover"
              />
            </el-carousel-item>
          </el-carousel>
          <el-empty v-else :image="empty" description="暂无图片" class="largeScreen-empty" style="height: 150px" />
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="24">
          <div class="title">
            <el-row :gutter="10">
              <el-col :span="16" class="time-period">
                <span>近{{ Someday }}天运行数据({{ timePeriod }})</span>
              </el-col>
              <el-col :span="4" class="escalate-records" v-if="isShowVideo">
                <span @click="handleChange">{{ ToggleButtonName }}</span>
              </el-col>
              <el-col :span="4" class="escalate-records">
                <span @click="ReportHandle">上报记录</span>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24" v-if="!isShowVideo">
          <div class="chart-box">
            <runData v-if="isShowECharts" :echartsData="currentPointInfo?.data" :deviceInfo="currentPointInfo?.info" />
            <el-empty v-else :image="empty" description="暂无数据" class="largeScreen-empty" />
          </div>
        </el-col>
        <!--      这个是带监控的那些模板-->
        <el-col :span="24" v-else>
          <div class="chart-box" v-if="ToggleButtonName === '视频监控'">
            <runData v-if="isShowECharts" :echartsData="currentPointInfo?.data" />
            <el-empty v-else :image="empty" description="暂无数据" class="largeScreen-empty" />
          </div>
          <div class="chart-box" v-else>
            <videoComManagement
              id="equipmentVideo"
              :camera-index-code="currentPointInfo?.info?.videMonitoring?.info?.data?.code"
              :value="currentPointInfo?.info?.videMonitoring?.info?.url"
              :video-type="currentPointInfo?.info?.videMonitoring?.type"
            />
          </div>
        </el-col>
      </el-row>
      <deviceRecording ref="deviceRecordingRef" :info="currentPointInfo?.info" v-if="currentPointInfo?.info" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.monitor-data-popup {
  background-image: url('@/assets/largescreen/xiangqing-kuang.png');
  background-size: 100% 100%;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  width: 700px;
  max-height: 80vh;
  overflow: hidden;
  color: white;
  box-sizing: border-box;
  padding: 20px;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
}

.popup-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #fff;
}

.close-btn {
  background: none;
  border: none;
  color: #fff;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: background-color 0.2s;

  &:hover {
    background: rgba(255, 255, 255, 0.1);
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: white;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #0be4f1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
<style scoped lang="scss">
.card-box {
  min-width: 600px;
  min-height: 200px;

  .title {
    background: url('@/assets/largescreen/title-pic.png') no-repeat center center;
    background-size: cover;
    width: 100%;
    height: 61px;
    line-height: 61px;
    padding-left: 20px;

    .time-period {
      color: white;
      font-family: PangMenZhengDao;
      font-size: 18px;
    }

    .escalate-records {
      color: #0be4f1;
      font-family: PangMenZhengDao;
      font-size: 18px;
      text-align: right;
      cursor: pointer;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .chart-box {
    width: 100%;
    height: 250px;
  }

  .capacity-box {
    width: 100%;
    height: 50px;
    border: 2px dashed #ccc;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .capacity-value {
      font-weight: 700;
      font-size: 16px;
      color: #00ffff;
    }

    .capacity-title {
      font-size: 12px;
      color: #fff;
      opacity: 0.8;
    }
  }

  .empty-box {
    width: 100%;
    height: 50px;
    color: #0be4f1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}
</style>
